<template>
  <section class="upload-files">
    <el-upload
      ref="upload"
      :headers="upload.headers"
      :action="upload.action"
      :auto-upload="autoupload"
      :accept="accept"
      :limit="limit"
      :multiple="true"
      :disabled="disabled"
      :file-list="files"
      :list-type="listtype"
      :before-upload="beforeupload"
      :on-success="uploadsuccess"
      :on-error="uploaderror"
      :on-exceed="onexceed"
    >
      <div class="el-upload__button" :class="{'uploadfile-error': error_, 'upload-disable': disabled}">
        <span class="icon">
          <svg-icon name="annex-icon" />
        </span>
        添加文件
      </div>
    </el-upload>
  </section>
</template>
<script>
import mixins from './../mixins'
import { getToken } from '@/utils/auth';
import { randomString } from '@/utils'
export default {
  name: 'VUploadFiles',
  mixins: [mixins],
  props: {
    option: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      upload: {
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        action: `${process.env.VUE_APP_BASE_API}/admin/sys-file/upload`,
        result: '',
        loading: false
      },
      files: [],
      result: ''
    }
  },
  computed: {
    accept () {
      return this.option.accept || ''
    },
    autoupload () {
      return this.option.autoupload
    },
    maxSize () {
      return this.option.maxSize || 5
    },
    limit () {
      return this.option.limit || 1
    },
    listtype () {
      return this.option.listtype || 'text'
    }
  },
  methods: {
    beforeupload (file) {
      const { maxSize } = this
      const size = file.size / 1024 / 1024 <= maxSize
      if (!size) {
        const { name } = file
        this.$confirm(`文件 ${name} 大小超过 ${(maxSize)}MB 限制`, '提示', {
          confirmButtonText: '重新上传',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          _this.$refs.upload.$children[0].handleClick()
        })
      }
      if (size) {
        this.upload.loading = true
      }
      return size
    },

    uploadsuccess ({ code, data, msg = '上传失败' }) {
      this.upload.loading = false
      if (code == 0) {
        this.upload.result = 'done'
        this.value.push(data)
        this.handleChange()
      } else {
        this.upload.result = 'fail'
        this.$message.error(msg)
        this.$refs.upload.clearFiles()
      }
    },

    uploaderror () {
      this.result = 'fail'
    },

    onexceed () {
      const { limit } = this
      this.$message.warning(`文件数量超出 ${limit}个 限制`)
    },

    getValue () {
      return this.value
    },

    setValue (v) {
      this.value = v
      this.files = (v || []).map(a => {
        return {
          name: a.name || randomString(8),
          url: a.url
        }
      })
      this.check()
    },

    setCheck () {
      const { required, value, autoupload } = this
      const { result, loading } = this.upload
      let error = false, error_message = ''
      if (required) {
        if (value.length == 0) {
          error = true;
          if (!result) {
            if (this.$refs.upload.uploadFiles.length <= 0) {
              error_message = '必填选项不能为空';
            } else {
              error = false
            }
          } else if (result === 'fail') {
            error_message = '上传失败'
          } else if (loading) {
            error_message = '上传中'
          }
        } else {
          error = false
        }
      } else {
        error = false
      }
      this.error_ = error
      this.error_message_ = error_message
      this.fieldCheck()
    },

    handleChange () {
      this.dispatch_event('filed-value-change', this.value)
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/var.scss';
.upload-files {
  /deep/ {
    .el-upload {
      width: 100%;
    }
  }
  .el-upload__button {
    text-align: left;
    height: 36px;
    line-height: 36px;
    background-image: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    background-color: $f9;
    padding: 0 15px;
    cursor: pointer;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: $f2;
    &:hover {
      color: $a1;
    }
    &.uploadfile-error {
      border: 1px solid $a3;
      &:hover {
        color: $f2;
      }
    }

    &.upload-disable {
      cursor: not-allowed;
      background-color: $f7;
      &:hover {
        color: $f2;
      }
    }
  }
}
</style>